# -*- coding: utf-8 -*-
# @Time    : 2019/12/16 9:41
# @Author  : CHEN Wang
# @Site    : 
# @File    : conn_dispatcher.py
# @Software: PyCharm


import time
from quant_researcher.quant.project_tool.logger.my_logger import LOG
from quant_researcher.quant.project_tool.db_operator import db_conn


HOW_TO_CREATE_CONN = {
    'derivative_data': db_conn.get_derivative_data_conn,
    'derivative_data_write': db_conn.get_derivative_data_write_conn,
    'basic_data': db_conn.get_basic_data_conn,
    'tk_factors': db_conn.get_tk_factors_conn,
}


def dispatcher(db_names):
    """
    批量创建数据库连接
    :param db_names: 数据库名称列表
    :return: dict, 数据库连接对象，和对应的创建时间
    """
    ans = {}
    for db_name in db_names:
        conn_got_ns = time.time()
        ans.update({
            db_name: HOW_TO_CREATE_CONN[db_name](),
            f'{db_name}_created_at': conn_got_ns
        })
        LOG.info(f'到 {db_name} 的连接的已创建，在：{conn_got_ns}')
    return ans


def close_them(conn_dict):
    """
    批量关闭数据库连接
    :param conn_dict: dict, 数据库连接对象，和对应的创建时间
    :return:
    """

    if conn_dict is None:
        return
    else:
        for k, v in conn_dict.items():
            if '_created_at' in k:
                continue
            closed_at = time.time()
            opened_at = conn_dict[f'{k}_created_at']
            conn_last = closed_at - opened_at
            # 2019年12月21日10:31:41，因为3.7版本才有计算纳秒的函数
            # conn_last = (closed_at - opened_at) / 10**9  # 1s = 10^9 ns
            conn_last = round(conn_last, 1)
            try:
                conn_dict[k].close()
                LOG.info(f'到 {k} 的连接的已关闭，'
                         f'持续：{conn_last}s，创建在：{opened_at}')
            except Exception as err:
                LOG.error(f'尝试关闭到 {k} 的连接时，发生错误：{err}，'
                          f'已持续：{conn_last}s，创建在：{opened_at}')


if __name__ == '__main__':
    close_them(None)
